package com.lsa.edmonds.chap10;

import java.io.IOException;
import java.util.Comparator;

import org.apache.commons.lang.ArrayUtils;

import com.lsa.helpers.Pair;
import com.lsa.helpers.Utils;
import com.lsa.helpers.heap.ArrayHeap;
import com.lsa.helpers.tree.ITree;
import com.lsa.helpers.tree.TgfTreeFactory;
import com.lsa.shenn.common.SorterTestCaseBase;

public class TestChap10 extends SorterTestCaseBase
{
	public void testHeapify() throws IOException
	{
		int [] array = new int[] {5, 9, 8, 6, 4, 7, 1, 3, 2};
		int [] expectedArray = new int[] {9, 6, 8, 5, 4, 7, 1, 3, 2};
		
		ITree<Pair<String, Object>> tree = TgfTreeFactory.createStringTreeFromArray(array);
		ITree<Pair<String, Object>> expectedTree = TgfTreeFactory.createStringTreeFromArray(expectedArray);
		
		TgfTreeFactory.saveStringTreeAsTgf(tree, "data/tree.tgf");
		TgfTreeFactory.saveStringTreeAsTgf(expectedTree, "data/expectedTree.tgf");
		
		HeapSort.heapify(1, array, array.length);
		assertTrue(Utils.compareArrays(array, expectedArray));
	}
	
	public void testMakeHeap() throws IOException{
		int [] array = new int[] {1, 7, 6, 8, 4, 9, 5, 2, 3};
		int [] expectedArray = new int[] {9, 8, 6, 7, 4, 1, 5, 2, 3};
		HeapSort.makeHeap(1, array);
//		ITree<Pair<String, Object>> tree = TgfTreeFactory.createStringTreeFromArray(array);
//		TgfTreeFactory.saveStringTreeAsTgf(tree, "data/test.tgf");
		assertTrue(Utils.compareArrays(array, expectedArray));
	}
	
	public void testMakeHeap2() throws IOException{
		int [] array = new int[] {1, 7, 6, 8, 4, 9, 5, 2, 3};
		int [] expectedArray = new int[] {9, 8, 6, 7, 4, 1, 5, 2, 3};
		HeapSort.makeHeap2(1, array);
//		ITree<Pair<String, Object>> tree = TgfTreeFactory.createStringTreeFromArray(array);
//		TgfTreeFactory.saveStringTreeAsTgf(tree, "data/test.tgf");
		assertTrue(Utils.compareArrays(array, expectedArray));
	}
	
	public void testHeapSort(){
		HeapSort sorter = new HeapSort();
		testSorter(sorter);
	}
	
	public void testArrayHeap() throws IOException{
		Integer [] array = new Integer[] {1, 7, 6, 8, 4, 9, 5, 2, 3};
		Integer [] expectedArray = new Integer[] {9, 7, 8, 3, 4, 6, 5, 1, 2};
		ArrayHeap<Integer> arrayHeap = new ArrayHeap<Integer>(new Comparator<Integer>(){
			@Override
			public int compare(Integer o1, Integer o2) {
				return o1 - o2;
			}
		});
		for (Integer i : array) {
			arrayHeap.insert(i);
		}
		Integer[] heapContent = arrayHeap.toArray(new Integer[0]);
		int[] heapContentPrimitive = ArrayUtils.toPrimitive(heapContent);
		assertTrue(Utils.compareArrays(heapContentPrimitive,
				ArrayUtils.toPrimitive(expectedArray)));
		
//		ITree<Pair<String, Object>> tree = TgfTreeFactory.createStringTreeFromArray(heapContentPrimitive);
//		TgfTreeFactory.saveStringTreeAsTgf(tree, "data/chap10/arrayHeap.tgf");
	}
	
	public void testArrayHeapBySorter(){
		TestArrayHeapPop sorter = new TestArrayHeapPop();
		testSorter(sorter);
	}
}
